﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using QWeiBoN.ViewModule;
using QWeiBoN.Objects;
using TencentWeiboSDK.Model;

namespace QWeiBoN.UserControler
{
    public partial class CommentsList : PhoneApplicationPage
    {

        #region 私有属性

        /// <summary>
        /// 微博ID
        /// </summary>
        private string weiboId;

        /// <summary>
        /// 评论对应的原始文本
        /// </summary>
        private string fatherText;

        /// <summary>
        /// 父微博发布人名称
        /// </summary>
        private string fatherName;

        /// <summary>
        /// 是否显示选择表情或者话题或者提及
        /// </summary>
        private bool isShowPop { get; set; }

        /// <summary>
        /// 微博评论列表服务
        /// </summary>
        private WeiboCommentsModel wcModel = new WeiboCommentsModel();

        /// <summary>
        /// 评论操作服务
        /// </summary>
        private TextCommentModel tcModel = new TextCommentModel();

        /// <summary>
        /// 拉取数据类型
        /// </summary>
        private enum EPollType
        {
            /// <summary>
            /// 默认，结果绑定到控件
            /// </summary>
            Default,
            /// <summary>
            /// 下一页，结果追加到末尾
            /// </summary>
            NextPage,
            /// <summary>
            /// 最新，结果插到开头
            /// </summary>
            Lastest
        }

        /// <summary>
        /// 加载数据的类型
        /// </summary>
        private EPollType pollType { get; set; }

        /// <summary>
        /// 是否正在拉取数据
        /// </summary>
        private bool isPolling { get; set; }

        /// <summary>
        /// 最后一条评论的时间戳
        /// </summary>
        private long lastTimestamp { get; set; }
        /// <summary>
        /// 第一条评论的时间戳
        /// </summary>
        private long firstTimestamp { get; set; }

        /// <summary>
        /// 最后一次刷新的时间
        /// </summary>
        private DateTime lastPollTime { get; set; }

        /// <summary>
        /// 手势是否是垂直拖拽
        /// </summary>
        private bool isVerticalDrag { get; set; }

        #endregion

        public CommentsList()
        {
            InitializeComponent();
            //RefreshCommentsList(PageFlag.First, 0);
        }

        #region 数据绑定

        /// <summary>
        /// 用于得到指定的评论列表
        /// </summary>
        private void RefreshCommentsList(PageFlag flag, long pagetime)
        {
            CommentProgressBar.IsIndeterminate = true;
            isPolling = true;
            lastPollTime = DateTime.Now;
            wcModel.getCommentList(weiboId, (int)flag, 10, pagetime, (callback) =>
            {
                isPolling = false;

                var newData = new List<Status>();
                callback.Data.ForEach(a =>
                {
                    //a.Nick = a.Nick + "：" + a.Text;
                    //var tmpFatherText = "|| @" + fatherName + ":" + fatherText;
                    //var tmpText = a.Origtext.Replace(tmpFatherText.Trim(), "").Trim();
                    //tmpFatherText = "||@" + fatherName + ":" + fatherText;
                    //tmpText = tmpText.Replace(tmpFatherText.Trim(), "").Trim();
                    //tmpFatherText = "|| @" + fatherName + "：" + fatherText;
                    //tmpText = tmpText.Replace(tmpFatherText.Trim(), "").Trim();
                    //tmpFatherText = "||@" + fatherName + "：" + fatherText;
                    //tmpText = tmpText.Replace(tmpFatherText.Trim(), "").Trim();
                    //tmpFatherText = "||@" + fatherName + ": " + fatherText;
                    //tmpText = tmpText.Replace(tmpFatherText.Trim(), "").Trim();


                    //tmpFatherText = "|| @" + fatherName + ": " + fatherText;
                    //tmpText = tmpText.Replace(tmpFatherText.Trim(), "").Trim();
                    //if (!string.IsNullOrWhiteSpace(tmpText))
                    //{
                    //a.Origtext = tmpText;
                    DateTime date = new DateTime(1970, 01, 01, 00, 00, 00);
                    date = date.AddSeconds(a.Timestamp);
                    a.From = date.Month + "月" + date.Day + "日 " + date.Hour + ":" + date.Minute + "  " + a.From;
                    if (null == a.Head || a.Head.Equals(""))
                    {
                        a.Head = "Resources/head_50.jpg";
                    }
                    newData.Add(a);
                    //}
                });

                var data = (IEnumerable<Status>)CommentsListView.ItemsSource;

                if (pollType == EPollType.NextPage)
                {
                    data = data.Concat(newData).ToList();
                    //data = newData.Concat(data).ToList();
                }
                else if (pollType == EPollType.Lastest)
                {
                    newData = newData.Where(t => t.Timestamp > firstTimestamp).ToList();
                    if (newData.Count > 0)
                    {
                        data = newData.Concat(data).ToList();
                        //data = data.Concat(newData).ToList();
                    }
                }
                else
                {
                    data = newData;
                }

                if (data != null && data.Count() > 0)
                {
                    lastTimestamp = data.LastOrDefault().Timestamp;

                    firstTimestamp = data.FirstOrDefault().Timestamp;
                }

                CommentsListView.ItemsSource = data;
                CommentsListView.UpdateLayout();

                // 对数据进行处理

                Dispatcher.BeginInvoke(() =>
                {
                    CommentProgressBar.IsIndeterminate = false;
                });
            });
        }

        #endregion

        #region 导航处理

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            FaceSelect.Selected = FaceSelected;
            if (NavigationContext.QueryString.ContainsKey(AppSetting.CommentsListTypeKey))
            {
                weiboId = NavigationContext.QueryString[AppSetting.CommentsListTypeKey];
                fatherName = NavigationContext.QueryString[AppSetting.CommentFatherName];
                if (NavigationContext.QueryString.ContainsKey(AppSetting.CommentsFatherText))
                {
                    fatherText = NavigationContext.QueryString[AppSetting.CommentsFatherText];
                }
                else
                {
                    fatherText = "";
                }
                if (!string.IsNullOrWhiteSpace(weiboId))
                {
                    CommentsListView.ItemsSource = null;
                    CommentsListView.UpdateLayout();
                    RefreshCommentsList(PageFlag.First, 0);
                }
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }

        #endregion

        #region barbutton 的事件处理

        /// <summary>
        /// 清理文字的按钮事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClearBarButton_Click(object sender, EventArgs e)
        {
            CommentTextBox.Text = string.Empty;
        }

        /// <summary>
        /// 表情按钮的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FaceBarButton_Click(object sender, EventArgs e)
        {
            if (isShowPop) { return; }
            isShowPop = true;
            CloseKeyboard();
            CommentProgressBar.IsIndeterminate = true;
            FaceSelect.Show(() =>
            {
                CommentProgressBar.IsIndeterminate = false;
            });
        }

        /// <summary>
        /// 评论按钮的事件处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommentBarButton_Click(object sender, EventArgs e)
        {
            var commentText = CommentTextBox.Text;
            if (string.IsNullOrWhiteSpace(commentText))
            {
                MessageBox.Show("评论内容不能为空");
                CommentTextBox.Focus();
            }
            else
            {
                tcModel.textComment(commentText, weiboId, (callBack) =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        CommentTextBox.Text = string.Empty;
                        CloseKeyboard();
                        pollType = EPollType.Lastest;
                        RefreshCommentsList(PageFlag.First, firstTimestamp);
                    });
                });
            }
        }

        /// <summary>
        /// 隐藏输入法
        /// </summary>
        private void CloseKeyboard()
        {
            Dispatcher.BeginInvoke(() => CBtn.Focus());
        }

        /// <summary>
        /// 用处理表情图片的选中
        /// </summary>
        /// <param name="face"></param>
        private void FaceSelected(string face)
        {
            Dispatcher.BeginInvoke(() =>
            {
                isShowPop = false;
                innerCommentContent(face);
                FaceSelect.Hide();
                CommentTextBox.Focus();
            });
        }

        /// <summary>
        /// 用于向CommentTextBox中插入内容
        /// </summary>
        /// <param name="face"></param>
        private void innerCommentContent(string face)
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (CommentTextBox.SelectedText.Length < 0)
                {
                    CommentTextBox.Select(CommentTextBox.SelectionStart, CommentTextBox.Text.Length - CommentTextBox.SelectionStart);
                    CommentTextBox.SelectedText = face + CommentTextBox.SelectedText;
                    CommentTextBox.SelectionStart += face.Length;
                }
                else
                {
                    CommentTextBox.SelectedText = face;
                }
                CommentTextBox.Focus();
            });
        }

        #endregion

        

        #region 手势处理

        /// <summary>
        /// 手势完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_GestureCompleted(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            if (isVerticalDrag || AppSetting.HightDragSensitivity)
            {
                var scrollView = AppSetting.FindChildOfType<ScrollViewer>(CommentsListView);
                if (null == scrollView)
                {
                    return;
                }
                // 移动至底部
                if (Math.Abs(scrollView.VerticalOffset - scrollView.ScrollableHeight) < 2)
                {
                    pollType = EPollType.NextPage;
                    RefreshCommentsList(PageFlag.Down, lastTimestamp);
                }
                else if (scrollView.VerticalOffset < 0.000001)
                {
                    pollType = EPollType.Lastest;
                    RefreshCommentsList(PageFlag.First, firstTimestamp);
                }
            }
        }

        /// <summary>
        /// 拖动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
        {
            if (e.Direction.ToString().Equals("Vertical"))
            {
                isVerticalDrag = true;
            }
        }

        #endregion

    }
}